<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  

  
  <title>SpringBoot系列—Druid（十） | 海晨忆的博客</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  
  
  <meta name="description" content="&amp;emsp;&amp;emsp;一个企业项目中最重要的部分那就是数据库了，对数据库的连接，读写是重中之重。在SpringBoot中数据库怎么连接呢？">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringBoot系列—Druid（十）">
<meta property="og:url" content="https://haichenyi.com/2019/09/05/SpringBoot系列—Druid（十）/index.html">
<meta property="og:site_name" content="海晨忆的博客">
<meta property="og:description" content="&amp;emsp;&amp;emsp;一个企业项目中最重要的部分那就是数据库了，对数据库的连接，读写是重中之重。在SpringBoot中数据库怎么连接呢？">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://haichenyi.com/uploads/article/2019-09-05/DataSourceProperties类.png">
<meta property="og:image" content="https://haichenyi.com/uploads/article/2019-09-05/yml文件.png">
<meta property="og:updated_time" content="2019-09-18T09:10:27.945Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="SpringBoot系列—Druid（十）">
<meta name="twitter:description" content="&amp;emsp;&amp;emsp;一个企业项目中最重要的部分那就是数据库了，对数据库的连接，读写是重中之重。在SpringBoot中数据库怎么连接呢？">
<meta name="twitter:image" content="https://haichenyi.com/uploads/article/2019-09-05/DataSourceProperties类.png">
  
    <link rel="alternate" href="/atom.xml" title="海晨忆的博客" type="application/atom+xml">
  
  
    <link rel="icon" href="/uploads/artistic_image/head.jpg">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link rel="stylesheet" href="/css/style.css">
  <link rel="stylesheet" href="/css/highlight.css">
  <script>
  let antiquityStorage = window.sessionStorage.getItem('antiquitySessionStorage');
  if (antiquityStorage == '' || antiquityStorage == null) {
    var antiquityLoader = '<div id="loaderbox"><div class="loader"><div class="load-roll"><div class="load-top"></div><div class="load-right"></div><div class="load-bottom"></div></div></div></div>';
    document.write(antiquityLoader);
    document.body.style.overflow = 'hidden'
  }
  </script>
</head>

<body>
  <div id="fullpage" class="mobile-nav-right">
    
      <div id="wrapper" style="background-image: url(/uploads/artistic_image/bg.jpg)" title="背景图片来自网络">
    
    
      <header id="header">
  <div id="nav-toggle" class="nav-toggle"></div>
  <div class="head-box global-width">
    <nav class="nav-box nav-right">
      
        <a class="nav-item" href="/" title
        
        >首页</a>
      
        <a class="nav-item" href="/archives" title
        
        >归档</a>
      
        <a class="nav-item" href="/about" title
        
        >简历</a>
      
    </nav>
  </div>
</header>
      <div id="middlecontent" title class="global-width sidebar-left">
        <section id="main"><article id="post-SpringBoot系列—Druid（十）" class="article global-container article-type-post" itemscope itemprop="blogPost">
  
    <header class="article-header">
      
  
    <h1 class="article-title" itemprop="name">
      SpringBoot系列—Druid（十）
    </h1>
  

    </header>
  
  <div class="article-meta">
    <a href="/2019/09/05/SpringBoot系列—Druid（十）/" class="article-date">
  <time datetime="2019-09-05T08:05:30.000Z" itemprop="datePublished">2019-09-05</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/Java-SpringBoot/">Java -SpringBoot</a>
  </div>

    
  </div>
  
    <span id="busuanzi_container_page_pv">
      本文总阅读量<span id="busuanzi_value_page_pv"></span>次
    </span>
  

  <div class="article-inner">
    
    <div class="article-content article-content-cloud doorframe mac" itemprop="articleBody">
      
        <p>&emsp;&emsp;一个企业项目中最重要的部分那就是数据库了，对数据库的连接，读写是重中之重。在SpringBoot中数据库怎么连接呢？</p>
<a id="more"></a>
<h3 id="数据库的连接"><a href="#数据库的连接" class="headerlink" title="数据库的连接"></a>数据库的连接</h3><p>&emsp;&emsp;这里以MySql为例，还不会用MySql数据库的童鞋，可以看我之前的博客，<a href="https://blog.csdn.net/qq_27634797/article/category/8050256" target="_blank" rel="noopener">数据库相关</a>。</p>
<p>&emsp;&emsp; <strong>第一步，</strong> 我们首先在pom.xml中添加jdbc相关的启动器。</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&lt;!--jdbc启动器--&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;spring-boot-starter-jdbc&lt;/artifactId&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br><span class="line">&lt;!--mysql驱动包--&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;mysql&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;</span><br><span class="line">    &lt;scope&gt;runtime&lt;/scope&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp; <strong>第二步，</strong> 在配置文件中配置连接数据库的信息：</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">spring:</span><br><span class="line">  datasource:</span><br><span class="line">    #连接数据库的账号</span><br><span class="line">    username: root</span><br><span class="line">    #连接数据库的密码</span><br><span class="line">    password: 123456</span><br><span class="line">    #连接数据库的url</span><br><span class="line">    url: jdbc:mysql://localhost:3306/company?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=GMT%2B8</span><br><span class="line">    #连接数据库的驱动类</span><br><span class="line">    #mysql8之前用的是：com.mysql.jdbc.Driver。</span><br><span class="line">    #mysql8之后用的是：com.mysql.cj.jdbc.Driver</span><br><span class="line">    driver-class-name: com.mysql.cj.jdbc.Driver</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp; 添加如上信息，就基本上完成了。测试一下连接就可以了。在我们的测试类中添加如下代码，看看打印的数据即可。</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">package com.haichenyi.springbootjdbc;</span><br><span class="line"></span><br><span class="line">import org.junit.Test;</span><br><span class="line">import org.junit.runner.RunWith;</span><br><span class="line">import org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line">import org.springframework.boot.test.context.SpringBootTest;</span><br><span class="line">import org.springframework.test.context.junit4.SpringRunner;</span><br><span class="line"></span><br><span class="line">import javax.sql.DataSource;</span><br><span class="line">import java.sql.Connection;</span><br><span class="line">import java.sql.SQLException;</span><br><span class="line"></span><br><span class="line">@RunWith(SpringRunner.class)</span><br><span class="line">@SpringBootTest</span><br><span class="line">public class SpringBootJdbcApplicationTests &#123;</span><br><span class="line">    @Autowired</span><br><span class="line">    DataSource dataSource;</span><br><span class="line"></span><br><span class="line">    @Test</span><br><span class="line">    public void contextLoads() throws SQLException &#123;</span><br><span class="line">        System.out.println(&quot;dataSource: &quot; + dataSource.getClass());</span><br><span class="line">        Connection connection = dataSource.getConnection();</span><br><span class="line">        System.out.println(&quot;connection: &quot; + connection);</span><br><span class="line">        connection.close();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp; 我们这里是测试数据库是否连接成功，我们才获取的这个连接，打印出来，我们项目里面实际操作数据库的时候，不需要我们获取这个连接，然后通过这个连接再去操作数据库。这是不需要，MyBatis通过Mapping注解直接操作数据库，我们只用写sql语句就可以了。</p>
<h3 id="Druid连接数据库"><a href="#Druid连接数据库" class="headerlink" title="Druid连接数据库"></a>Druid连接数据库</h3><p>&emsp;&emsp; DRUID是阿里巴巴开源平台上一个数据库连接池实现，它结合了C3P0、DBCP、PROXOOL等DB池的优点，同时加入了日志监控，可以很好的监控DB池连接和SQL的执行情况，可以说是针对监控而生的DB连接池，据说是目前最好的连接池。</p>
<p>&emsp;&emsp; <strong>上面的配置继续保留。</strong></p>
<p>&emsp;&emsp; <strong>第一步：</strong> 我们在pom.xml里面添加druid的依赖：</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- https://mvnrepository.com/artifact/com.alibaba/druid --&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;com.alibaba&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;druid&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;1.1.20&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp; <strong>第二步：</strong> 在yml文件中添加如下代码：</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line">spring:</span><br><span class="line">  # 数据库访问配置</span><br><span class="line">  datasource:</span><br><span class="line">    #账号</span><br><span class="line">    username: root</span><br><span class="line">    #密码</span><br><span class="line">    password: 123456</span><br><span class="line">    #连接的url</span><br><span class="line">    url: jdbc:mysql://localhost:3306/company?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=GMT%2B8</span><br><span class="line">    #驱动类</span><br><span class="line">    driver-class-name: com.mysql.cj.jdbc.Driver</span><br><span class="line">    # 主数据源，默认的</span><br><span class="line">    type: com.alibaba.druid.pool.DruidDataSource</span><br><span class="line"></span><br><span class="line">    # 下面为连接池的补充设置，应用到上面所有数据源中</span><br><span class="line">    # 初始化大小，最小，最大</span><br><span class="line">    initialSize: 5</span><br><span class="line">    minIdle: 5</span><br><span class="line">    maxActive: 20</span><br><span class="line">    # 配置获取连接等待超时的时间</span><br><span class="line">    maxWait: 60000</span><br><span class="line">    # 配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒</span><br><span class="line">    timeBetweenEvictionRunsMillis: 60000</span><br><span class="line">    # 配置一个连接在池中最小生存的时间，单位是毫秒</span><br><span class="line">    minEvictableIdleTimeMillis: 300000</span><br><span class="line">    validationQuery: SELECT 1 FROM DUAL</span><br><span class="line">    testWhileIdle: true</span><br><span class="line">    testOnBorrow: false</span><br><span class="line">    testOnReturn: false</span><br><span class="line">    # 打开PSCache，并且指定每个连接上PSCache的大小</span><br><span class="line">    poolPreparedStatements: true</span><br><span class="line">    maxPoolPreparedStatementPerConnectionSize: 25</span><br><span class="line">    # 配置监控统计拦截的filters，去掉后监控界面sql无法统计，&apos;wall&apos;用于防火墙</span><br><span class="line">    filters: stat,wall,logback</span><br><span class="line">    # 通过connectProperties属性来打开mergeSql功能；慢SQL记录</span><br><span class="line">    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500</span><br><span class="line">    # 合并多个DruidDataSource的监控数据</span><br><span class="line">    useGlobalDataSourceStat: true</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp; 这样，就可以了。继续运行刚才的测试方法，你会发现，打印数据里面数据源已经变成了DruidDataSource。</p>
<p>&emsp;&emsp; 你如果是debug运行的，并且，你的断点打在connection那里，你会发现，我们yml文件中的补充配置，没起作用，是为什么呢？</p>
<p>&emsp;&emsp; 我们按住CTRL，鼠标左键点补充配置里面的任意一个变量，都点不动，我们点上面的type，url等等，都能点，我们点过去看，我们会发现跳到了 <strong>DataSourceProperties</strong> 。这个类，顾名思义这是数据源配置文件类。我们大致看一下这个类的代码：</p>
<p><img src="/uploads/article/2019-09-05/DataSourceProperties类.png" alt="DataSourceProperties类.png"></p>
<p>&emsp;&emsp; 用红色框框，框出来的地方是不是很眼熟？</p>
<p>&emsp;&emsp; 首先，我们先看注解 <strong>@ConfigurationProperties，</strong> 这个注解就是表示这个类是配置类，然后，我们看括号里面的参数 <strong>prefix，</strong> 顾名思义：前缀，前置代码。</p>
<p><img src="/uploads/article/2019-09-05/yml文件.png" alt="yml文件.png"></p>
<p>&emsp;&emsp; 如上图，上面的红色框框的内容，就由prefix决定，下面红色框框的内容，就由这个类的变量决定。我们上面的补充设置不起作用，就是因为这个配置文件里面没有这些变量，SpringBoot识别不了，所以，不起作用。SpringBoot不是万能的，它配置了的东西，可以识别，没有配置的，识别不了。</p>
<p>&emsp;&emsp; 怎么样让上面的补充配置起作用呢？有多种方式：</p>
<p>&emsp;&emsp; <strong>第一种方式如下：</strong> 简单粗暴，添加一个配置类即可</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">package com.haichenyi.springbootjdbc.config;</span><br><span class="line"></span><br><span class="line">import com.alibaba.druid.pool.DruidDataSource;</span><br><span class="line">import org.springframework.boot.context.properties.ConfigurationProperties;</span><br><span class="line">import org.springframework.context.annotation.Bean;</span><br><span class="line">import org.springframework.context.annotation.Configuration;</span><br><span class="line"></span><br><span class="line">import javax.sql.DataSource;</span><br><span class="line"></span><br><span class="line">@Configuration</span><br><span class="line">public class JdbcConfig &#123;</span><br><span class="line">    @ConfigurationProperties(prefix = &quot;spring.datasource&quot;)</span><br><span class="line">    @Bean</span><br><span class="line">    public DataSource dataSource()&#123;</span><br><span class="line">        return new DruidDataSource();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp; 这个方式就相当于，把我们上面的这个 <strong>DataSourceProperties</strong>配置类，换成了 <strong>DruidDataSource</strong>类。</p>
<p>&emsp;&emsp; <strong>第二种方式如下：</strong> 比较麻烦，也不算特别麻烦：说白了就是加载局部配置。</p>
<p>&emsp;&emsp;首先，在resources目录下，新建一个jdbc.properties文件</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">#账号</span><br><span class="line">druid.datasource.username=root</span><br><span class="line">#密码</span><br><span class="line">druid.datasource.password=123456</span><br><span class="line">#连接的url</span><br><span class="line">druid.datasource.url=jdbc:mysql://localhost:3306/company?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=GMT%2B8</span><br><span class="line">#驱动类</span><br><span class="line">druid.datasource.driverClassName=com.mysql.cj.jdbc.Driver</span><br><span class="line"># 主数据源，默认的</span><br><span class="line"># druid.datasource.type=com.alibaba.druid.pool.DruidDataSource</span><br><span class="line"># 下面为连接池的补充设置，应用到上面所有数据源中</span><br><span class="line"># 初始化大小，最小，最大</span><br><span class="line">druid.datasource.initialSize=5</span><br><span class="line">druid.datasource.minIdle=5</span><br><span class="line">druid.datasource.maxActive=20</span><br><span class="line"># 配置获取连接等待超时的时间</span><br><span class="line">druid.datasource.maxWait=60000</span><br><span class="line"># 配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒</span><br><span class="line">druid.datasource.timeBetweenEvictionRunsMillis=60000</span><br><span class="line"># 配置一个连接在池中最小生存的时间，单位是毫秒</span><br><span class="line">druid.datasource.minEvictableIdleTimeMillis=300000</span><br><span class="line">druid.datasource.validationQuery=SELECT 1 FROM DUAL</span><br><span class="line">druid.datasource.testWhileIdle=true</span><br><span class="line">druid.datasource.testOnBorrow=false</span><br><span class="line">druid.datasource.testOnReturn=false</span><br><span class="line"># 打开PSCache，并且指定每个连接上PSCache的大小</span><br><span class="line">druid.datasource.poolPreparedStatements=true</span><br><span class="line">druid.datasource.maxPoolPreparedStatementPerConnectionSize=25</span><br><span class="line"># 配置监控统计拦截的filters，去掉后监控界面sql无法统计，&apos;wall&apos;用于防火墙</span><br><span class="line">druid.datasource.filters=stat,wall,logback</span><br><span class="line"># 通过connectProperties属性来打开mergeSql功能；慢SQL记录</span><br><span class="line">druid.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500</span><br><span class="line"># 合并多个DruidDataSource的监控数据</span><br><span class="line">druid.datasource.useGlobalDataSourceStat=true</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp;就是把我们刚才在全局配置中配置的信息，在专门的jdbc的配置文件中配置一遍。然后，修改我们的JdbcConfig类。如下：</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br></pre></td><td class="code"><pre><span class="line">package com.haichenyi.springbootjdbc.config;</span><br><span class="line"></span><br><span class="line">import com.alibaba.druid.pool.DruidDataSource;</span><br><span class="line">import org.springframework.beans.factory.annotation.Value;</span><br><span class="line">import org.springframework.context.annotation.Bean;</span><br><span class="line">import org.springframework.context.annotation.Configuration;</span><br><span class="line">import org.springframework.context.annotation.PropertySource;</span><br><span class="line"></span><br><span class="line">import javax.sql.DataSource;</span><br><span class="line">import java.sql.SQLException;</span><br><span class="line"></span><br><span class="line">@Configuration</span><br><span class="line">@PropertySource(value = &quot;classpath:config/jdbc.properties&quot;, ignoreResourceNotFound = true)</span><br><span class="line">public class JdbcConfig &#123;</span><br><span class="line">    @Value(&quot;$&#123;druid.datasource.username&#125;&quot;)</span><br><span class="line">    private String username;</span><br><span class="line">    @Value(&quot;$&#123;druid.datasource.password&#125;&quot;)</span><br><span class="line">    private String password;</span><br><span class="line">    @Value(&quot;$&#123;druid.datasource.url&#125;&quot;)</span><br><span class="line">    private String url;</span><br><span class="line">    @Value(&quot;$&#123;druid.datasource.driverClassName&#125;&quot;)</span><br><span class="line">    private String driverClassName;</span><br><span class="line">    @Value(&quot;$&#123;druid.datasource.initialSize&#125;&quot;)</span><br><span class="line">    private Integer initialSize;</span><br><span class="line">    @Value(&quot;$&#123;druid.datasource.minIdle&#125;&quot;)</span><br><span class="line">    private Integer minIdle;</span><br><span class="line">    @Value(&quot;$&#123;druid.datasource.maxActive&#125;&quot;)</span><br><span class="line">    private Integer maxActive;</span><br><span class="line">    @Value(&quot;$&#123;druid.datasource.maxWait&#125;&quot;)</span><br><span class="line">    private Long maxWait;</span><br><span class="line">    @Value(&quot;$&#123;druid.datasource.timeBetweenEvictionRunsMillis&#125;&quot;)</span><br><span class="line">    private Long timeBetweenEvictionRunsMillis;</span><br><span class="line">    @Value(&quot;$&#123;druid.datasource.minEvictableIdleTimeMillis&#125;&quot;)</span><br><span class="line">    private Long minEvictableIdleTimeMillis;</span><br><span class="line">    @Value(&quot;$&#123;druid.datasource.validationQuery&#125;&quot;)</span><br><span class="line">    private String validationQuery;</span><br><span class="line">    @Value(&quot;$&#123;druid.datasource.testWhileIdle&#125;&quot;)</span><br><span class="line">    private Boolean testWhileIdle;</span><br><span class="line">    @Value(&quot;$&#123;druid.datasource.testOnBorrow&#125;&quot;)</span><br><span class="line">    private Boolean testOnBorrow;</span><br><span class="line">    @Value(&quot;$&#123;druid.datasource.testOnReturn&#125;&quot;)</span><br><span class="line">    private Boolean testOnReturn;</span><br><span class="line">    @Value(&quot;$&#123;druid.datasource.maxPoolPreparedStatementPerConnectionSize&#125;&quot;)</span><br><span class="line">    private Integer maxPoolPreparedStatementPerConnectionSize;</span><br><span class="line">    @Value(&quot;$&#123;druid.datasource.poolPreparedStatements&#125;&quot;)</span><br><span class="line">    private Boolean poolPreparedStatements;</span><br><span class="line">    @Value(&quot;$&#123;druid.datasource.filters&#125;&quot;)</span><br><span class="line">    private String filters;</span><br><span class="line">    @Value(&quot;$&#123;druid.datasource.connectionProperties&#125;&quot;)</span><br><span class="line">    private String connectionProperties;</span><br><span class="line">    @Value(&quot;$&#123;druid.datasource.useGlobalDataSourceStat&#125;&quot;)</span><br><span class="line">    private Boolean useGlobalDataSourceStat;</span><br><span class="line"></span><br><span class="line">    @Bean</span><br><span class="line">    public DataSource dataSource() throws SQLException &#123;</span><br><span class="line">        DruidDataSource druidDataSource = new DruidDataSource();</span><br><span class="line">        druidDataSource.setUsername(username);</span><br><span class="line">        druidDataSource.setPassword(password);</span><br><span class="line">        druidDataSource.setUrl(url);</span><br><span class="line">        druidDataSource.setDriverClassName(driverClassName);</span><br><span class="line">        druidDataSource.setInitialSize(initialSize);</span><br><span class="line">        druidDataSource.setMinIdle(minIdle);</span><br><span class="line">        druidDataSource.setMaxActive(maxActive);</span><br><span class="line">        druidDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);</span><br><span class="line">        druidDataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);</span><br><span class="line">        druidDataSource.setValidationQuery(validationQuery);</span><br><span class="line">        druidDataSource.setTestOnBorrow(testOnBorrow);</span><br><span class="line">        druidDataSource.setTestOnReturn(testOnReturn);</span><br><span class="line">        druidDataSource.setTestWhileIdle(testWhileIdle);</span><br><span class="line">        druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);</span><br><span class="line">        druidDataSource.setPoolPreparedStatements(poolPreparedStatements);</span><br><span class="line">        druidDataSource.setFilters(filters);</span><br><span class="line">        druidDataSource.setConnectionProperties(connectionProperties);</span><br><span class="line">        druidDataSource.setUseGlobalDataSourceStat(useGlobalDataSourceStat);</span><br><span class="line">        return druidDataSource;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp;就是加载配置文件，然后在DataSource里面赋值。这样，就可以了。</p>
<h3 id="Druid后台监控"><a href="#Druid后台监控" class="headerlink" title="Druid后台监控"></a>Druid后台监控</h3><p>&emsp;&emsp;之所以用Druid连接池，还有很大一部分原因就是它的监控功能。它能很好的监控DB连接池和SQL语句的执行情况。在上面的JdbcConfig类中添加如下两个方法即可。</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 配置Druid监控</span><br><span class="line"> *</span><br><span class="line"> * @return StatViewServlet</span><br><span class="line"> */</span><br><span class="line">@Bean</span><br><span class="line">public ServletRegistrationBean servletRegistrationBean() &#123;</span><br><span class="line">    ServletRegistrationBean&lt;StatViewServlet&gt; bean = new ServletRegistrationBean&lt;&gt;(new StatViewServlet(), &quot;/druid/*&quot;);</span><br><span class="line">    Map&lt;String, String&gt; map = new HashMap&lt;&gt;();</span><br><span class="line">    //访问的用户名密码</span><br><span class="line">    map.put(StatViewServlet.PARAM_NAME_USERNAME, &quot;haichenyi&quot;);</span><br><span class="line">    map.put(StatViewServlet.PARAM_NAME_PASSWORD, &quot;123456&quot;);</span><br><span class="line">    //允许访问的ip，默认是所有ip</span><br><span class="line">    map.put(StatViewServlet.PARAM_NAME_ALLOW, &quot;&quot;);</span><br><span class="line">    //禁止访问的ip</span><br><span class="line">    map.put(StatViewServlet.PARAM_NAME_DENY, &quot;192.168.1.1&quot;);</span><br><span class="line">    bean.setInitParameters(map);</span><br><span class="line">    return bean;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * 配置一个监控的filter</span><br><span class="line"> *</span><br><span class="line"> * @return WebStatFilter</span><br><span class="line"> */</span><br><span class="line">@Bean</span><br><span class="line">public FilterRegistrationBean filterRegistrationBean() &#123;</span><br><span class="line">    FilterRegistrationBean&lt;WebStatFilter&gt; bean = new FilterRegistrationBean&lt;&gt;();</span><br><span class="line">    bean.setFilter(new WebStatFilter());</span><br><span class="line">    Map&lt;String, String&gt; map = new HashMap&lt;&gt;();</span><br><span class="line">    //移除这些监听</span><br><span class="line">    map.put(WebStatFilter.PARAM_NAME_EXCLUSIONS, &quot;*.js,*.css,/druid/*,*.gif,*.jpg,*.png&quot;);</span><br><span class="line">    bean.setInitParameters(map);</span><br><span class="line">    //拦截所有请求，全部都要走druid监听</span><br><span class="line">    bean.setUrlPatterns(Collections.singletonList(&quot;/*&quot;));</span><br><span class="line">    return bean;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp;注释写的很清楚了，控制台怎么访问呢？ <strong><a href="http://localhost:8080/druid" target="_blank" rel="noopener">http://localhost:8080/druid</a></strong>。访问控制台</p>

      
    </div>
    
      <footer class="article-footer">
        完
      </footer>
    
  </div>
  
    
<nav id="article-nav">
  <div class="article-nav-block">
    
      <a href="/2019/09/07/SpringBoot系列—MyBatis（十一）/" id="article-nav-newer" class="article-nav-link-wrap">
        <strong class="article-nav-caption"></strong>
        <div class="article-nav-title">
          
            SpringBoot系列—MyBatis（十一）
          
        </div>
      </a>
    
  </div>
  <div class="article-nav-block">
    
      <a href="/2019/09/05/SpringBoot系列—自定义拦截器（九）/" id="article-nav-older" class="article-nav-link-wrap">
        <div class="article-nav-title">SpringBoot系列—自定义拦截器（九）</div>
        <strong class="article-nav-caption"></strong>
      </a>
    
  </div>
</nav>

    
  
  
</article>
</section>
        <aside id="sidebar">
  
    <div class="widget-box">
  <div class="avatar-box avatar-item">
    <img class="avatar" src="/uploads/artistic_image/head.jpg" title="头像来自网络"></img>
    <h3 class="avatar-name">
      
        海晨忆
      
    </h3>
    <p class="avatar-slogan">
      先谋生，再谋爱。人间值得，未来可期。
    </p>
  </div>
</div>


  
    
  <div class="widget-box">
    <h3 class="widget-title">分类</h3>
    <div class="widget">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/Android-Socket/">Android -Socket</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-加密算法/">Android -加密算法</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-常用功能/">Android -常用功能</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-框架/">Android -框架</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-源码解析/">Android -源码解析</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-自定义view/">Android -自定义view</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-设计模式/">Android -设计模式</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/JAVA-并发/">JAVA -并发</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Java-SpringBoot/">Java -SpringBoot</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Tomcat/">Tomcat</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/kotlin/">kotlin</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/数据库-JDBC/">数据库 -JDBC</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/数据库-MySQL/">数据库 -MySQL</a></li></ul>
    </div>
  </div>


  
    

  
    
  
    
  <div class="widget-box">
    <h3 class="widget-title">归档</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/07/">July 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/11/">November 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/10/">October 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/09/">September 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/08/">August 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/07/">July 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/06/">June 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/10/">October 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/05/">May 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/03/">March 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/02/">February 2018</a></li></ul>
    </div>
  </div>

  
    
  <div class="widget-box">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2021/07/27/JAVA—公平锁，非公平锁，悲观锁，乐观锁，死锁/">JAVA—公平锁，非公平锁，悲观锁，乐观锁，死锁</a>
          </li>
        
          <li>
            <a href="/2021/07/19/JAVA—线程同步器AQS/">JAVA—线程同步器AQS</a>
          </li>
        
          <li>
            <a href="/2021/07/07/Android模拟点击/">Android模拟点击</a>
          </li>
        
          <li>
            <a href="/2019/11/27/SpringBoot系列-消息-RabbitMQ-（二十）/">SpringBoot系列-消息(RabbitMQ)（二十）</a>
          </li>
        
          <li>
            <a href="/2019/11/13/SpringBoot系列-Docker（十九）/">SpringBoot系列-Docker（十九）</a>
          </li>
        
      </ul>
    </div>
  </div>

  
      <div class="widget-box">
    <h3 class="widget-title">友情链接</h3>
    <div class="widget">
      
        <a class="hrf" style="display: block;" href="https://github.com/haichenyi" title target='_blank'
        >Github</a>
      
        <a class="hrf" style="display: block;" href="https://www.jianshu.com/u/6077ee440c37" title target='_blank'
        >简书</a>
      
        <a class="hrf" style="display: block;" href="https://blog.csdn.net/qq_27634797" title target='_blank'
        >CSDN</a>
      
    </div>
  </div>

  
</aside>
      </div>
      <footer id="footer">
  <div class="foot-box footers global-width">
    &copy;2017-2021 海晨忆 &nbsp;&nbsp;
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span id="busuanzi_container_site_pv">阁下是第<span id="busuanzi_value_site_pv"></span>个访客</span>
  </div>
</footer>
      <script src="https://code.jquery.com/jquery-2.0.3.min.js"></script>
<script>
if (!window.jQuery) {
var script = document.createElement('script');
script.src = "/js/jquery-2.0.3.min.js";
document.body.write(script);
}
</script>

  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/script.js"></script>



    </div>
    <nav id="mobile-nav" class="mobile-nav-box">
  <div class="mobile-nav-img mobile-nav-top"></div>
  
    <a href="/" class="mobile-nav-link">首页</a>
  
    <a href="/archives" class="mobile-nav-link">归档</a>
  
    <a href="/about" class="mobile-nav-link">简历</a>
  
  <div class="mobile-nav-img  mobile-nav-bottom"></div>
</nav>    
  </div>
</body>
</html>